var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
    data: {
        dataLoaded: false,

        couponsVisible: false,
        useCoupon: true, //是否使用代金券

        curCoupon: null, //当前选中的券
        payAmount: 0, //实付金额
        paying: false,
        stopClick: false,
        orderId: ''

    },

    onLoad: function(options) {
        this._options = options;

        common.initApp({
            extSuc: () => {
                this._fetch();
            },
            loginSuc: () => {
                this.$loginSuc();
            },
            sysInfoSuc: (sysInfo) => {
                this.setData({
                    winHei: app.getWinHei(),
                });
            },
        });
    },

    _fetch() {
        var {
            orderId
        } = this._options;

        ajax.G({
            url: '/market/Pay/payOrderInfo',
            data: {
                order_id: orderId,
            },
            success: (res) => {
                var {
                    order_info: orderInfo,
                    coupon_list: couponList,
                    order_goods: goodsList,
                    best_coupon_id: bestCouponId
                } = res.result;
                var goodsAmount = 0;
                var curCoupon;

                couponList.forEach((coupon) => {
                    if (bestCouponId == coupon.id) {
                        curCoupon = coupon;
                        coupon.checked = true;
                    } else {
                        coupon.checked = false;
                    }
                })
                goodsList.forEach((goods) => {
                    goodsAmount += parseInt(goods.amount);
                });
                orderInfo.goodsAmount = goodsAmount;

                this.setData({
                    dataLoaded: true,
                    orderInfo,
                    couponList,
                    goodsList,
                    curCoupon,
                });

                this._calMoney();
            }
        });
    },

    /**
     * 显示代金券选择列表
     * @return {[type]} [description]
     */
    _showCouponList() {
        this.setData({
            couponsVisible: true
        });
    },

    /**
     * 选择代金券
     * @param  {[type]} evt [description]
     * @return {[type]}     [description]
     */
    _selectCoupon(evt) {
        var {
            couponList
        } = this.data;
        var curCoupon;

        couponList.forEach((coupon) => {
            if (evt.detail.value == coupon.id) {
                curCoupon = coupon;
                coupon.checked = true;
            } else {
                coupon.checked = false;
            }
        });

        this.setData({
            couponList,
            curCoupon,
        });
        this._calMoney();
    },

    /**
     * 隐藏代金券列表
     * @return {[type]} [description]
     */
    _hideCouponList() {
        this.setData({
            couponsVisible: !this.data.couponsVisible
        });
    },

    /**
     * 禁用或启用代金券列表
     * @param  {[type]} evt [description]
     * @return {[type]}     [description]
     */
    _disabledCoupon(evt) {
        this.setData({
            useCoupon: evt.detail.value,
        });
        this._calMoney();
    },

    /**
     * 计算实付金额
     * @return {[type]} [description]
     */
    _calMoney() {
        var {
            orderInfo,
            curCoupon,
            useCoupon
        } = this.data;
        var orderAmount = parseFloat(orderInfo.order_amount); //订单金额
        var couponAmount = parseFloat(curCoupon ? curCoupon.coupon_amount : 0);
        var payAmount = 0;

        if (useCoupon) {
            payAmount = orderAmount - couponAmount;
        } else {
            payAmount = orderAmount;
        }
        if (payAmount < 0) {
            payAmount = 0;
        }

        this.setData({
            payAmount: parseFloat(payAmount).toFixed(2)
        });
    },

    /**
     * 支付
     * @return {[type]} [description]
     */
    _payOrder() {
        var {
            orderId
        } = this._options;
        var {
            curCoupon
        } = this.data;

        this.setData({
            paying: true,
            stopClick: true
        })

        setTimeout(() => {
            this.setData({
                stopClick: false
            })
        }, 5000);

        ajax.P({
            url: '/market/Pay/toPay',
            data: {
                order_id: orderId,
                coupon_id: curCoupon ? curCoupon.id : '',
                open_id: app.getOpenId()
            },
            success: (res) => {
                var {
                    payType,
                    wxPayParams,
                    orderId,
                    payAmount
                } = res.result;

                if (payType == 0) { //使用代金券支付成功
                    this.setData({
                        paying: false,
                        orderId,
                        payAmount
                    })
                    util.alert('代金券抵扣成功', () => {
                        wx.redirectTo({
                            url: '/pages/paySuccess/index?orderId=' + orderId + '&totalPrice=' + payAmount
                        });
                    })

                } else if (payType == 1) { //支付宝
                } else if (payType == 2) { //微信
                    this._paySuccess(wxPayParams, orderId, payAmount);
                }
            },
            fail: (res) => {
                this.setData({
                    paying: false
                })
            }
        });
    },

    /**
     * 微信支付成功回调
     */
    _paySuccess(wxPayParams, orderId, payAmount) {
        var _self = this;
        this.setData({
            paying: false,
            orderId
        })
        if (typeof wxPayParams == 'string') {
            wxPayParams = JSON.parse(wxPayParams);
        }

        wxPayParams.success = function() {
            wx.redirectTo({
                url: '/pages/paySuccess/index?orderId=' + orderId + '&totalPrice=' + payAmount
            });
        }
        this.$wxPay(wxPayParams);
    },

}));